<?php
/**
 * This file is part of PHPlaza (xhttp://code.google.com/p/phplaza)
 * This file is licensed under the GNU Lesser General Public License
 *      http://www.gnu.org/licenses/lgpl.html
 *
 * No warranty is given, express or implied. Use at your own risk.
 */

namespace core;

use core::collections as collections;

class Viewstate
{
	public static function run(core::Page $page)
	{		
		$state = core::services::ServiceRegistrator::getInstance()->getStateService();

		if (!$state->previousPageExists())
		{
			self::initializeApplication();
			self::initializeNewPage($page);
		} else if ($state->getPreviousPage() !== $page->getId())
		{
			self::initializeNewPage($page);
		} else {
			$page->__setState($state->getPageState());
		}
		
		$data = new collections::PostData();
		$data->merge(new collections::GetData());
		
		self::handleRequest($data, $page);
		
		$state->setPageState($page->__getState());
	}
	
	protected static function initializeApplication()
	{
	}
	
	protected static function initializeNewPage(core::Page $page)
	{
		$state = core::services::ServiceRegistrator::getInstance()->getStateService();

		$state->setCurrentPage($page);
		$page->initialize();
	}
	
	protected static function handleRequest(collections::IList $data, core::Page $page)
	{
		$components = $page->getComponents();
		
		foreach($data as $key => $value)
		{
			if (isset($components[$key]) && $components[$key] instanceof core::components::IEventGenerator)
			{
				$components[$key]->_handleRequest($value);
			}
		}
	}
}